class GroupsController < ApplicationController
 layout "application", :except => [ :report ] 

  def show
    @group = Group.find(params[:id])
    return self.unauthorized unless self.current_user.can('view:group', @group)
    @runners = @group.runners
    add_page_token(@group.name)
  end

  def map
    @group = Group.find(params[:id])
    return self.unauthorized unless self.current_user.can('view:group', @group)
    @runners = @group.runners
    @incentives = Incentive.find(:all)
    @landmarks = Landmarks.find(:all)
    @index = params[:index].to_i if params[:index]
    add_page_token(@group.name)
  end

  def new
    @group = Group.new
  end

  def edit
    @group = Group.find(params[:id])
    return self.unauthorized unless self.current_user.can('edit:group', @group)
    add_page_token(@group.name)
  end

  def create
    @group = Group.new(params[:group])
    
    return self.unauthorized unless self.current_user.can('create:group', @group)

    if @group.save
      flash[:notice] = 'Group was successfully created.'
      redirect_to(@group)
    else
      render :action => "new"
    end
  end

  def update
    @group = Group.find(params[:id])
    
    return self.unauthorized unless self.current_user.can('edit:group', @group)
    add_page_token(@group.name)

    if @group.update_attributes(params[:group])
      flash[:notice] = 'Group was successfully updated.'
      redirect_to(@group)
    else
      render :action => "edit"
    end
  end

  def destroy
    @group = Group.find(params[:id])
    
    return self.unauthorized unless self.current_user.can('delete:group', @group)
    site = @group.site
    @group.destroy

    redirect_to site_path(site)
  end

  def report
    @group = Group.find(params[:id])
    
    return self.unauthorized unless self.current_user.can('view:group', @group)
    @runners = @group.runners
    headers['Content-Type'] = "application/vnd.ms-excel" 
    headers['Content-Disposition'] = 'attachment; filename="excel-export.csv"'

    data = ""
    data << @group.name+"\n"
    data << "runner name, runners current miles, runners goal\n"
    
    for runner in @runners
      data << runner.name+","+runner.distance_cache.to_s+","+runner.goal.to_s+"\n"
    end
    @data = data
  end
end
